<template>

  <el-row :gutter="10" class="mb8">
    <el-col :span="1.5">
      <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['scm:scmProjectProducts:add']">新增</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['scm:scmProjectProducts:edit']">修改</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['scm:scmProjectProducts:remove']">删除
      </el-button>
    </el-col>
<!--    <el-col :span="1.5">-->
<!--      <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['scm:scmProjectProducts:export']">导出</el-button>-->
<!--    </el-col>-->
    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :search="false"
                   :columns="columns"></right-toolbar>
  </el-row>

  <el-table
      v-loading="loading"
      :data="scmProjectProductsList"
      @selection-change="handleSelectionChange"
      row-key="id"
      lazy :scrollbar-always-on="true"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :cell-style="cellStyle"
  >
    <el-table-column type="selection" width="55" align="center"/>
    <!--    <el-table-column label="ID" align="center" prop="id" />-->
    <!--    <el-table-column label="项目ID" align="center" prop="projectId" />-->

    <!--    <el-table-column label="产品ID" align="center" prop="productId" />-->
    <el-table-column label="图号" align="center" prop="drawingNumber" width="98" fixed>
      <!--      <template #default="scope">-->
      <!--        {{scope.row.scmProduct.drawingNumber}} {{scope.row.scmProduct.version}}-->
      <!--      </template>-->
    </el-table-column>
    <el-table-column label="版本" align="center" prop="version" fixed v-if="columns[0].visible"/>
    <el-table-column label="内版本" align="center" prop="internalVersion" fixed v-if="columns[1].visible"/>
    <el-table-column label="品名" align="left" prop="productName" :show-overflow-tooltip="true" width="120" fixed v-if="columns[2].visible">
      <template #default="scope">
        <el-popover placement="right" :width="500" trigger="hover" >
          <template #reference>
            <span><el-badge is-dot v-if="scope.row.history && scope.row.history.length > 0"/></span>
          </template>
          <template #default>
            <el-table :data="scope.row.history">
              <el-table-column width="98" property="createTime" label="日期" :formatter="dateFormat">
                <template #default="historyScope">{{ dateFormat(historyScope.row, null, historyScope.row.createTime, 0) }}</template>
              </el-table-column>
              <el-table-column width="200" property="oldValue" label="修改前">
                <template #default="historyScope"> {{ historyScope.row.oldValue }} </template>
              </el-table-column>
              <el-table-column width="200" property="newValue" label="修改后">
                <template #default="historyScope"> {{ historyScope.row.newValue }} </template>
              </el-table-column>
            </el-table>
<!--            <div>-->
<!--              <p><strong>2025-07-29:</strong> {{ scope.row.scmProduct.drawingNumber }} <i class="el-icon-edit"></i>   {{ scope.row.scmProduct.drawingNumber }}</p>-->
<!--              <p><strong>版本:</strong> {{ scope.row.scmProduct.version }}</p>-->
<!--              <p><strong>内部版本:</strong> {{ scope.row.scmProduct.internalVersion }}</p>-->
<!--              <p><strong>型号:</strong> {{ scope.row.scmProduct.model }}</p>-->
<!--              <p><strong>颜色:</strong> {{ scope.row.scmProduct.color }}</p>-->
<!--            </div>-->
          </template>
        </el-popover>
        <span>{{ scope.row.productName }}</span>
      </template>
    </el-table-column>

    <el-table-column label="材质" align="center" prop="material" v-if="columns[3].visible" />
    <el-table-column label="阻燃等级" align="center" prop="inflamingRetardingLevel" v-if="columns[3].visible" />
    <el-table-column label="规格" align="center" prop="specification" v-if="columns[4].visible"/>
    <el-table-column label="型号" align="center" prop="model" v-if="columns[4].visible"/>
    <el-table-column label="颜色" align="center" prop="color" v-if="columns[5].visible"/>
    <el-table-column label="图纸构成" align="center" prop="drawingComposition" v-if="columns[3].visible" />
    <el-table-column label="产品状态" align="center" prop="projectProductStatus" width="78" v-if="columns[6].visible">
      <template #default="scope">
        <dict-tag :options="scm_product_status" :value="scope.row.projectProductStatus"/>
      </template>
    </el-table-column>
    <el-table-column label="客户状态" align="center" prop="customerStatus" width="98" v-if="columns[7].visible">
      <template #default="scope">
        <dict-tag :options="scm_project_customer_status" :value="scope.row.customerStatus"/>
      </template>
    </el-table-column>
    <el-table-column label="供应商状态" align="center" prop="supplierStatus" width="98" v-if="columns[8].visible">
      <template #default="scope">
        <dict-tag :options="scm_project_supplier_status" :value="scope.row.supplierStatus"/>
      </template>
    </el-table-column>
    <el-table-column label="采购类型" align="center" prop="purchaseCategory" width="98" v-if="columns[9].visible">
      <template #default="scope">
        <dict-tag :options="scm_purchase_category" :value="scope.row.purchaseCategory"/>
      </template>
    </el-table-column>
    <el-table-column label="部品类型" align="center" prop="demandType" width="98" v-if="columns[10].visible">
      <template #default="scope">
        <dict-tag :options="scm_demand_type" :value="scope.row.demandType"/>
      </template>
    </el-table-column>
    <el-table-column label="沟通内容" align="center" prop="remark" :show-overflow-tooltip="true" width="100"
                     v-if="columns[11].visible"/>
    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
      <template #default="scope">
        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                   v-hasPermi="['scm:scmProjectProducts:edit']">修正
        </el-button>
        <el-button link type="primary" icon="Sell" @click="handleUpgrade(scope.row)"
                   v-hasPermi="['scm:scmProducts:edit']">升级
        </el-button>
        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                   v-hasPermi="['scm:scmProjectProducts:remove']">删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
  />

  <!-- 添加或修改项目产品需求对话框 -->
  <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
    <el-form ref="scmProjectProductsRef" :model="form" :rules="rules" label-width="99px">
<!--      <el-row :gutter="24">-->
<!--        <el-col :span="6">-->
<!--          <el-form-item label="项目ID" prop="projectId">-->
<!--            <el-input v-model="form.projectId" placeholder="请输入项目ID" disabled/>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-form-item label="产品ID" prop="productId">-->
<!--            <el-input v-model="form.productId" placeholder="请输入产品ID"/>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--      </el-row>-->
      <el-row :gutter="24">
<!--        <el-col :span="6">-->
<!--          <el-form-item label="产品状态" prop="projectProductStatus">-->
<!--            <el-select v-model="form.projectProductStatus" placeholder="请选择产品项目中的状态">-->
<!--              <el-option v-for="dict in scm_product_status" :key="dict.value" :label="dict.label"-->
<!--                         :value="parseInt(dict.value)"-->
<!--              ></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="6">
          <el-form-item label="客户状态" prop="customerStatus">
            <el-select v-model="form.customerStatus" placeholder="请选择客户状态">
              <el-option v-for="dict in scm_project_customer_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商状态" prop="supplierStatus">
            <el-select v-model="form.supplierStatus" placeholder="请选择供应商状态">
              <el-option v-for="dict in scm_project_supplier_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6" >
          <el-form-item label="选择产品" prop="productId"  v-if="form.id == null" >
            <el-select
                v-model="form.productId" filterable remote reserve-keyword placeholder="请输入图号" clearable
                :remote-method="remoteMethodOfProduct" @change="handleChangeOfProduct" :loading="loading" >
              <el-option
                  v-for="item in optionsOfProduct" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采购类型" prop="purchaseCategory">
            <el-select v-model="form.purchaseCategory" placeholder="请选择采购类型">
              <el-option v-for="dict in scm_purchase_category" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="部品类型" prop="demandType">
            <el-select v-model="form.demandType" placeholder="请选择部品类型">
              <el-option v-for="dict in scm_demand_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="图号" prop="drawingNumber" >
            <el-input v-model="form.drawingNumber" placeholder="请输入图号" :disabled="form.productId != null" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="版本号" prop="version">
            <el-input v-model="form.version" placeholder="请输入版本号"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="内部版本" prop="internalVersion">
            <el-input v-model="form.internalVersion" placeholder="最新内部版本号" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态" prop="productStatus">
            <el-select v-model="form.scmProduct.productStatus" placeholder="请选择状态" disabled>
              <el-option
                  v-for="dict in scm_product_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="品名" prop="productName">
            <el-input v-model="form.productName" placeholder="请输入产品名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="材质" prop="material">
            <el-input v-model="form.material" placeholder="请输入材质"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="阻燃等级" prop="inflamingRetardingLevel">
            <el-input v-model="form.inflamingRetardingLevel" placeholder="请输入阻燃等级"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="规格" prop="specification">
            <el-input v-model="form.specification" placeholder="请输入规格"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="型号" prop="model">
            <el-input v-model="form.model" placeholder="请输入型号"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="颜色" prop="color">
            <el-input v-model="form.color" placeholder="请输入颜色"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="图纸构成" prop="drawingComposition">
            <el-input v-model="form.drawingComposition" placeholder="请输入图纸构成"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
<!--        <el-col :span="6">-->
<!--          <el-form-item label="图纸名" prop="drawingAttachmentName">-->
<!--            <el-input v-model="form.scmProduct.drawingAttachmentName" placeholder="请输入上传图纸名字"/>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="图纸" prop="drawingAttachmentUrl">
<!--            <file-upload v-model="form.scmProduct.drawingAttachmentUrl"/>-->
            <div style="display: flex; gap: 10px; align-items: center; width: 100%">
              <el-input :value="form.scmProduct.drawingAttachmentUrl ? form.scmProduct.drawingAttachmentUrl.substring(form.scmProduct.drawingAttachmentUrl.lastIndexOf('/') + 1) : '' " placeholder="请上传图纸" style="flex: 2;" disabled />
              <file-upload v-model="form.scmProduct.drawingAttachmentUrl" :isShowTip="false"/>
              <el-button size="default" type="text" @click="$download.resource(form.scmProduct.drawingAttachmentUrl,false)">下载</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产品备注" prop="productRemark">
            <el-input v-model="form.scmProduct.productRemark" type="textarea" placeholder="请输入内容" :rows="2"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="沟通内容" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="2" />
          </el-form-item>
        </el-col>
      </el-row>


      <el-divider content-position="center">产品子图信息</el-divider>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleAddScmProductsSub">添加子图</el-button>
        </el-col>
      </el-row>
      <el-table :data="form.scmProduct && form.scmProduct.scmProductsSubList ? form.scmProduct.scmProductsSubList : []" :row-class-name="rowScmProductsSubIndex"
                ref="scmProductsSub">
<!--        <el-table-column type="selection" width="50" align="center"/>-->
        <el-table-column label="序号" align="center" prop="index" width="50"/>
        <el-table-column label="子图号" align="center"  width="80">子图号</el-table-column>
        <el-table-column label="子图号" prop="drawingSubNumber" >
          <template #default="scope">
            <el-input v-model="scope.row.drawingSubNumber" placeholder="请输入子图号" />
          </template>
        </el-table-column>
        <!--          <el-table-column label="子图名" prop="drawingSubAttachmentName" width="150">-->
        <!--            <template #default="scope">-->
        <!--              <el-input v-model="scope.row.drawingSubAttachmentName" placeholder="请输入子图名" />-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <el-table-column label="附件地址" prop="drawingSubAttachmentUrl" >
          <template #default="scope">
            <el-input v-model="scope.row.drawingSubAttachmentUrl" placeholder="文件名字，上传后自动生成" :disabled="true"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="290">
          <template #default="scope">
            <div style="display: flex; gap: 10px; align-items: center; width: 100%">
              <file-upload v-model="scope.row.drawingSubAttachmentUrl" :isShowTip="false"/>
              <el-button size="default" type="text" icon="Download" @click="$download.resource(scope.row.drawingSubAttachmentUrl,false)">下载</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['scm:scmProducts:remove']">删除</el-button>
            </div>
            <!--              <el-button link type="primary" icon="Upload" @click="handleUpdate(scope.row)" v-hasPermi="['scm:scmProducts:edit']">上传</el-button>-->
            <!--              <el-button link type="primary" icon="Download" @click="handleUpdate(scope.row)" v-hasPermi="['scm:scmProducts:edit']">下载</el-button>-->
            <!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['scm:scmProducts:remove']">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup name="ScmProjectProductsTable">
import { listScmProjectProducts, getScmProjectProducts, delScmProjectProducts, addScmProjectProducts, updateScmProjectProducts } from "@/api/scm/scmProjectProducts";
import { listScmProductsHistoryByProductIds } from "@/api/scm/scmProductsHistory"

// import { ref, defineProps, defineEmits, onMounted } from "vue";
// import {ref,} from "vue";
// 确保在文件顶部导入必要的函数
import { ref, reactive, toRefs, getCurrentInstance, watch } from "vue";

import DictTag from "@/components/DictTag";
import {listScmProducts} from "@/api/scm/scmProducts.js";
import {getProjects} from "@/api/scm/projects.js";

const {proxy} = getCurrentInstance();
const {
  scm_demand_type,
  scm_project_customer_status,
  scm_product_status,
  scm_project_supplier_status,
  scm_purchase_category
} = proxy.useDict(
    "scm_demand_type",
    "scm_project_customer_status",
    "scm_product_status",
    "scm_project_supplier_status",
    "scm_purchase_category"
);

const props = defineProps({
  tableData: {
    type: Array,
    // required: true,
  },
  loading: {
    type: Boolean,
    default: false,
  },
  projectId: {
    type: String,
    required: true
  }
});

const tableData = ref([]);
const loading = ref(false);
const scmProjectProductsList = ref([]);
const open = ref(false);
const total = ref(0);
const title = ref("");
const single = ref(true)
const multiple = ref(true)
const ids = ref([])
const showSearch = ref(true)


const emit = defineEmits(["selectionChange", "update", "delete"]);

// function handleSelectionChange(selection) {
//   emit("selectionChange", selection);
// }

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// function handleUpdate(row) {
//   emit("update", row);
// }

// function handleDelete(row) {
//   emit("delete", row);
// }

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: props.projectId,
    productId: null,
    projectProductStatus: null,
    customerStatus: null,
    supplierStatus: null,
  },
  rules: {
    projectId: [
      {required: true, message: "项目ID不能为空", trigger: "blur"},
    ],
    customerStatus: [
      {required: true, message: "客户状态不能为空", trigger: "change"},
    ],
    supplierStatus: [
      {required: true, message: "供应商状态不能为空", trigger: "change"},
    ],
  },
});

const {queryParams, form, rules} = toRefs(data);

// const localProjectId = ref(props.projectId);
// 监听 projectId 变化
watch(
    () => props.projectId,
    (newVal) => {
      console.log('projectId changed to:', newVal);
      queryParams.value.projectId = newVal; // 更新本地变量
      getList();
    }
);

/** 查询项目产品需求列表 */
function getList() {
  loading.value = true;
  listScmProjectProducts(queryParams.value).then((response) => {
    scmProjectProductsList.value = proxy.handleTree(response.rows, "id");
    // 先获取所有数据
    // const allData = response.rows;
    // 或者根据其他条件过滤，例如：
    // scmProjectProductsList.value = allData.filter(item => item.projectProductStatus === 1);

    total.value = response.total;
    loading.value = false;

    // 获取所有产品的ID
    const productIds = response.rows.map(item => item.productId);
    // console.log('productIds:', productIds.length);
    if (productIds.length === 0){
      return;
    }


        // 获取产品历史记录
    listScmProductsHistoryByProductIds(productIds).then(historyResponse => {
      // 创建一个映射，以productId为键，历史记录数组为值
      const historyMap = {};
      if (historyResponse.rows && Array.isArray(historyResponse.rows)) {
        historyResponse.rows.forEach(historyItem => {
          if (!historyMap[historyItem.productId]) {
            historyMap[historyItem.productId] = [];
          }
          historyMap[historyItem.productId].push(historyItem);
        });
      }
      // console.log('historyMap:', historyMap);

      // 将历史记录映射到产品列表中
      const updateProductsWithHistory = (products) => {
        return products.map(product => {
          return {
            ...product,
            history: historyMap[product.productId] || []
          };
        });
      };

      // 更新主列表和树形结构
      const updatedList = updateProductsWithHistory(response.rows);
      scmProjectProductsList.value = proxy.handleTree(updatedList, "id");
      console.log('scmProjectProductsList:', scmProjectProductsList);
    });
  });
}

getList();

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectId: queryParams.value.projectId,
    productId: null,
    projectProductStatus: null,
    customerStatus: 1,
    supplierStatus: 0,
    purchaseCategory: 0,
    demandType: 0,
    drawingNumber: null,
    version: null,
    internalVersion: null,
    productName:  null,
    material: null,
    inflamingRetardingLevel:  null,
    specification: null,
    model: null,
    color: null,
    drawingComposition: null,
    remark: null,
    scmProduct: {
      id: null,
      drawingNumber: null,
      version: null,
      internalVersion: null,
      productName: null,
      model: null,
      color: null,
      productStatus: null,
      drawingAttachmentName: null,
      drawingAttachmentUrl: null,
      productRemark: null,
      scmProductsSubList: [],
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null
    },
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
  };
  proxy.resetForm("scmProjectProductsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加项目产品需求";
  projectInquiry();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getScmProjectProducts(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改项目产品需求";
  });
}

/** 升级按钮操作 */
function handleUpgrade(row) {
  reset();
  const _id = row.id || ids.value;
  getScmProjectProducts(_id).then((response) => {
    form.value = response.data;
    form.value.id = null;
    form.value.productId = null;
    open.value = true;
    title.value = "升级项目产品需求";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["scmProjectProductsRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateScmProjectProducts(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addScmProjectProducts(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
      .confirm('是否确认删除项目产品需求编号为"' + _ids + '"的数据项？')
      .then(function () {
        return delScmProjectProducts(_ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => {
      });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("scm/scmProjectProducts/export", {
    ...queryParams.value,
  }, `scmProjectProducts_${new Date().getTime()}.xlsx`);
}

/** 查询项目信息 */
function projectInquiry() {
  const _projectId = queryParams.value.projectId
  if (_projectId == null || _projectId === '' || _projectId === 0 || _projectId === "0" )
    return;
  getProjects(_projectId).then(response => {
    form.value.purchaseCategory = response.data.purchaseCategory;
    form.value.demandType = response.data.demandType;
  });
}

// 列显隐信息
const columns = ref([
  {key: 0, label: `版本`, visible: true},
  {key: 1, label: `内版本`, visible: true},
  {key: 2, label: `品名`, visible: true},
  {key: 3, label: `绘图配置`, visible: true},
  {key: 4, label: `型号`, visible: true},
  {key: 5, label: `颜色`, visible: true},
  {key: 6, label: `产品状态`, visible: true},
  {key: 7, label: `客户状态`, visible: true},
  {key: 8, label: `供应商状态`, visible: true},
  {key: 9, label: `采购类型`, visible: true},
  {key: 10, label: `部品类型`, visible: true},
  {key: 11, label: `沟通内容`, visible: true}
]);

const cellStyle = ({row, column, rowIndex, columnIndex}) => {
  // 第一行（rowIndex === 0）且第四列（columnIndex === 3）
  // columnIndex为3是因为前面还有selection列（type="selection"）
  // if (rowIndex === 0 && columnIndex === 3) {
  //   return { backgroundColor: 'yellow' }
  // }
  // 获取当前列绑定的字段名
  // const fieldName = column.property;
  //  console.log('当前列绑定的字段名:', fieldName);
  //  console.log(row['scmProduct'][fieldName]);
  // if (row[fieldName] !== undefined && row[fieldName] !== null && row['scmProduct'][fieldName] !== undefined && row['scmProduct'][fieldName] !== null){
  //   if (row[fieldName] !== row['scmProduct'][fieldName]){
  //     return { backgroundColor: 'yellow' }
  //   }
  // }
  // return {}

  try {
    // 获取当前列绑定的字段名
    const fieldName = column.property;

    // 检查基本条件
    if (!fieldName) return {};

    // 确保 row 和 scmProduct 都存在
    if (!row || !row.scmProduct) return {};

    // 确保两个字段都存在再进行比较
    const projectValue = row[fieldName];
    const productValue = row.scmProduct[fieldName];

    // 只有当两个值都存在且不相等时才高亮显示
    if (projectValue !== undefined &&
        projectValue !== null &&
        productValue !== undefined &&
        productValue !== null &&
        projectValue !== productValue) {
      return { backgroundColor: 'yellow' }
    }

    return {};
  } catch (error) {
    // 发生错误时返回默认样式
    console.warn('Error in cellStyle:', error);
    return {};
  }
}

const dateFormat = (row, column, cellValue, index) => {
  if (!cellValue) return '';
  // 将日期格式化为 yyyy-mm-dd
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};


//产品 图号 下拉菜单
const optionsOfProduct = ref([]);
const productList = ref([]);
const queryParamsOfProduct = ref({});

function resetQueryOfProduct() {
  queryParamsOfProduct.value = {
    pageNum: 1,
    pageSize: 50,
    drawingNumber: undefined,
    productName: undefined,
    nickName: undefined,
    status: undefined,
    deptId: undefined
  }
}
function remoteMethodOfProduct(query) {
  console.log('query', query);
  resetQueryOfProduct();
  console.log('productList.value.length', productList.value.length);
  // if (productList.value.length === 0){
    queryParamsOfProduct.value.drawingNumber = query.trim();
    listProductSelect();
  // }
}
function initializeProductOptions(productId) {
  console.log('productId', productId)
  resetQueryOfProduct();
  queryParamsOfProduct.value.productId = productId;
  listProductSelect();
}
function handleChangeOfProduct(value) {
  console.log('value', value);
  // form.value.productId = value;
  const product = productList.value.find(product => product.id === value);
  // form.value.ownerProductName = productList.value.find(product => product.productId === value).nickName;
  form.value.drawingNumber = product.drawingNumber;
  form.value.version = product.version;
  form.value.internalVersion = product.internalVersion;
  form.value.productStatus = product.productStatus;
  form.value.productName = product.productName;
  form.value.material = product.material;
  form.value.inflamingRetardingLevel = product.inflamingRetardingLevel;
  form.value.specification = product.specification;
  form.value.model = product.model;
  form.value.color = product.color;
  form.value.drawingComposition = product.drawingComposition;
  form.value.scmProduct = product;
}
function listProductSelect() {
  listScmProducts(queryParamsOfProduct.value).then(response => {
    productList.value = response.rows;

    optionsOfProduct.value = productList.value.map(product => ({
      label: product.drawingNumber + ' / ' + product.version + ' / ' + product.internalVersion,
      value: product.id,
    }));
  });
}

/** 产品子表序号 */
function rowScmProductsSubIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

</script>

<style>
.yellow-bg {
  background-color: yellow !important;
}
</style>